<style lang="less" rel="stylesheet/less" type="text/less">
.api-box {
  font-size: 20px;
  width: 500px;
  .api-text {
    font-size: 16px;
  }
  .try-out {
    margin-left: 50px;
  }
  .radio-tips {
    color: red;
  }
  .backButton {
    margin-bottom: 18px;
  }
}
</style>
<template>
  <div class="api-box">
    <Button class="backButton" type="primary" size="large" @click="toIndex">返回列表</Button>
    <Form ref="formData" :model="form_data" :rules="ruleInline">
      <Form-item prop="phone" class="form-input">
        <i-input v-model="form_data.phone" placeholder="请输入手机号码" name="panx-user">
          <Select
            slot="prepend"
            v-model="form_data.area_code"
            style="width:70px"
            name="create-area"
          >
            <Option
              v-for="item in area_code_list"
              :value="item.dial_code"
              :key="item.code"
            >+{{ item.dial_code }}</Option>
          </Select>
        </i-input>
      </Form-item>
      <Form-item label="ApiKey名称" prop="name">
        <Input v-model="form_data.name" name="app-name" type="text" placeholder="请输入ApiKey名称"></Input>
      </Form-item>
      <FormItem label="ApiKey描述" prop="description">
        <Input
          v-model="form_data.description"
          :autosize="{minRows: 3,maxRows: 5}"
          type="textarea"
          placeholder="请输入ApiKey描述"
        ></Input>
      </FormItem>
      <Form-item>
        <div class="api-text">资费方案</div>
        <RadioGroup v-model="form_data.type" size="large" @on-change="changeType">
          <Radio label="按时间计费" />
          <Radio label="永久授权" class="try-out" />
        </RadioGroup>
      </Form-item>

      <Form-item v-if="form_data.type==='按时间计费'" label="开始时间与结束时间" props="start_end">
        <DatePicker
          v-model="form_data.start_end"
          :options="startOption"
          :style="{width: '260px'}"
          type="datetimerange"
          placement="top"
          placeholder="请选择开始时间与结束时间"
          @on-change="changeEDDate"
        />
      </Form-item>

      <Form-item>
        <Button
          size="large"
          type="primary"
          name="create__submit"
          @click="handleSubmit('formData')"
        >创建</Button>
      </Form-item>
    </Form>
  </div>
</template>
<script>
import qs from "qs";
export default {
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号码不能为空!"));
      }
      if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    const validateNull = (rule, value, callback) => {
      if (!value) {
        if (rule.field == "name") {
          return callback(new Error("名称不能为空!"));
        }
        return callback(new Error("描述不能为空!"));
      }
      if (/\s/.test(value)) {
        if (rule.field == "name") {
          return callback(new Error("名称不能为存在空格!"));
        }
        return callback(new Error("描述不能存在空格!"));
      }
      callback();
    };
    return {
      real_started_at: null,
      real_ended_at: null,
      area_code_list: [],
      startOption: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      form_data: {
        name: "",
        description: "",
        type: "按时间计费",
        area_code: "86",
        phone: null,
        start_end: []
      },
      ruleInline: {
        phone: [
          {
            validator: validatePhone,
            required: true,

            trigger: "blur,change"
          }
        ],
        name: [
          {
            validator: validateNull,
            required: true,
            trigger: "blur,change"
          }
        ],
        description: [
          {
            required: true,
            validator: validateNull,
            trigger: "blur,change"
          }
        ]
      }
    };
  },
  created() {
    this.getAreaCode();
  },
  methods: {
    handleSubmit(name) {
      if (this.form_data.start_end) {
        if (
          this.form_data.start_end[0] === "" &&
          this.form_data.type === "按时间计费"
        ) {
          this.$Message.error("开始时间与结束时间不能为空!");
        } else {
          this.$refs[name].validate(valid => {
            if (valid) {
              // 创建APIkey请求

              this.APICreate(this.form_data);
            } else {
              this.$Message.error("你输入的信息有误");
            }
          });
        }
      } else {
        this.$refs[name].validate(valid => {
          if (valid) {
            // 创建APIkey请求
            this.APICreate(this.form_data);
          } else {
            this.$Message.error("你输入的信息有误");
          }
        });
      }
    },

    //  获取地区区号
    getAreaCode() {
      this.axios
        .get(`${window.location.origin}/admin/api/v1/get-areacode`)

        .then(({ data }) => {
          if (Number(data.code) !== 200) throw new Error(data.error);

          this.area_code_list = data.areacodes;
        })

        .catch(err => {
          this.$Message.error(err.message || err.statusText);
        });
    },
    APICreate(param) {
      this.$Spin.show();
      if (param.type === "按时间计费") {
        param.start_time = this.real_started_at;
        param.end_time = this.real_ended_at;

        this.$emit("APICreate", param);
      } else {
        this.$emit("APICreate", param);
      }
    },
    toIndex() {
      this.$emit("back");
    },

    changeEDDate(date) {
      this.changeDate = date[0].slice(0, 10);
      if (date[0] === "") {
        this.real_started_at = null;
        this.real_ended_at = null;
      } else {
        this.real_started_at = this.$moment(date[0])
          .utc()
          .format();
        this.real_ended_at = this.$moment(date[1])
          .utc()
          .format();
      }
    },

    handleReset() {
      this.form_data.name = "";
      this.form_data.phone = null;
      this.form_data.description = "";
      this.form_data.area_code = "86";
      this.form_data.type = "按时间计费";
      this.form_data.start_end = null;
      this.real_started_at = null;
      this.real_ended_at = null;
    },
    changeType(type) {
      if (type === "永久授权") {
        this.form_data.start_end = null;
        this.real_started_at = null;
        this.real_ended_at = null;
      }
    }
  }
};
</script>